
package cn.yangliu.ex;

import cn.hutool.core.util.StrUtil;
import cn.yangliu.model.IResult;
import lombok.Getter;

import java.util.Objects;

/**
 * the type of serial-port-tool
 *
 * <p>
 * .
 *
 * @author 杨柳
 * @date 2024-05-29
 */
@Getter
public class ToolException extends RuntimeException implements IResult {

    private static final long serialVersionUID = 194906846739586856L;

    /** The code. */
    private final String code;

    /** The msg. */
    private final String msg;

    public ToolException(IResult code) {
        this.code = code.getCode();
        this.msg = code.getMsg();
    }

    public ToolException(IResult code, Throwable cause) {
        super(cause);
        this.code = code.getCode();
        this.msg = code.getMsg();
    }

    public ToolException(IResult result, String... additions) {
        this.code = result.getCode();
        this.msg = formatMessage(result.getMsg(), additions);
    }

    public ToolException(IResult result,Throwable cause, String... additions) {
        super(cause);
        this.code = result.getCode();
        this.msg = formatMessage(result.getMsg(), additions);
    }

    private static String formatMessage(String message, String... additions) {
        if (Objects.isNull(additions) || additions.length == 0) {
            return message;
        }
        if (message.contains("%s")
                && StrUtil.count(message, "%s") == additions.length) {
            return String.format(message, (Object[]) additions);
        }
        StringBuilder sb = new StringBuilder(message);
        for (Object addition : additions) {
            sb.append(",").append(addition);
        }
        return sb.toString();
    }
}
